package com.fms.kccc.task;

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.util.Log;

public class GetTask extends AsyncTask<Void, Void, String> {

	private String url;
	private OnGetTaskListener listener;

	public GetTask(String url) {
		super();
		this.url = url;
	}

	@Override
	protected void onPreExecute() {
		if (listener != null) {
			listener.onPreExecute();
		}
	}

	@Override
	protected String doInBackground(Void... value) {
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpClient httpClient = new DefaultHttpClient(params);
		HttpGet httpGet = new HttpGet(url);
		Log.d("kccc", url);
		try {
			HttpResponse httpResponse = httpClient.execute(httpGet);
			int status = httpResponse.getStatusLine().getStatusCode();
			if (status == HttpStatus.SC_OK) {
				HttpEntity getResponseEntity = httpResponse.getEntity();
				return EntityUtils.toString(getResponseEntity);
			}

		} catch (IOException e) {
			httpGet.abort();
		}
		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		if (result != null) {
			if (listener != null) {
				listener.onSuccess(result);
			}
		} else {
			if (listener != null) {
				listener.onFail();
			}
		}
	}

	public void setOnGetTaskListener(OnGetTaskListener listener) {
		this.listener = listener;
	}

	public interface OnGetTaskListener {
		public void onPreExecute();

		public void onSuccess(String result);

		public void onFail();
	}

}
